package com.dingreading.cloud.admin.util.redis;

import com.dingreading.cloud.admin.util.bean.OrderFormV3Util;
import com.dingreading.cloud.common.util.RedisParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * Redis过期回调监听方法
 */
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        super.onMessage(message, pattern);

        if (message != null) {
            // 过期key，可以设置成订单号
            String expiredKey = message.toString();
            if (StringUtils.isNotBlank(expiredKey) && expiredKey.startsWith(RedisParam.MALL_CODE)) {
                // 取消商城订单业务逻辑
                System.out.println("expiredKey = " + expiredKey);
                String[] codes = StringUtils.split(expiredKey, "_");
                if (codes != null && codes.length == 2)
                    OrderFormV3Util.cancelOrderFormAndShopCarts(codes[1]);
            }
        }
    }
}
